import { FN } from "@Tea/model";
import { InitHttpReturnType, isSuccessCode, useElMessageBox, useGloablLoading } from "@Tea/utils";
import { ElMessage } from "element-plus";
import { Ref, isRef } from "vue";

const handleHttpCommonLoading = (
  handleData: Parameters<typeof httpCommonHandle>[0]["loading"],
  closeOrOpen: boolean
) => {
  if (isRef(handleData)) {
    handleData.value = closeOrOpen
  } else {
    const { showLoading, closeLoading } = handleData()
    if (closeOrOpen) {
      showLoading()
    } else {
      console.log(234);
      closeLoading()
    }
  }
}
export const httpCommonHandle = async<T>(
  {
    loading, callBack, successMsg, onSuccess
  }: {
    loading: Ref<boolean> | typeof useGloablLoading,
    callBack: (...args: any[]) => Promise<InitHttpReturnType<T>>,
    successMsg?: string
    onSuccess?: FN
  }
) => {
  handleHttpCommonLoading(loading, true)

  try {
    const { code, msg } = await callBack()
    
    handleHttpCommonLoading(loading, false)

    if (isSuccessCode(code)) {
      ElMessage({
        type: "success",
        message: msg || successMsg
      })
      onSuccess?.()
    } else {
      handleHttpCommonLoading(loading, false)
      useElMessageBox({
        type: "error",
        content: msg
      })
    }
  } catch (e) {
    handleHttpCommonLoading(loading, false)
  }
}